<?php

/* Generates an excerpt for the post if none is set in the database */

require_once 'classes/LightPressPlugin.php';

class PostExcerpt extends LightPressPlugin {

    var $constructor_args = array('excerpt_length' => 'Maximum length of excerpt');
    var $default_context = LP_CONTEXT_ALL;
    var $description = 'Excerpt generation';
    
    var $active = true;
    var $hooks = array('get_posts', 'get_posts_loop');
    
    var $_frontend;
    
    var $excerpt_length = 204;
    
    function PostExcerpt(&$frontend, $args, $dummy_run=false) {
        $this->LightPressPlugin($frontend, $args, $dummy_run);
    }
    
    function run($hook, &$post) {
        if (!$this->active || !is_array($post))
            return;
        
        if (($hook == 'get_posts') && isset($post['f'])) {
            // modify query to include excerpt data
            if (!strstr($post['f'], 'post_excerpt'))
                $post['f'] .= ', p.post_excerpt';
		}
        elseif (($hook == 'get_posts_loop') && 
                isset($post['post_excerpt']) && empty($post['post_excerpt'])) {
            // no excerpt exists so we must create one
            $excerpt = '';
            $count = 0;
            foreach (explode(' ', strip_tags($post['post_content'])) as $word) {
                $count += strlen($word) + 1;
                if ($count > $this->excerpt_length)
                    break;
                $excerpt .= " $word";
            }
            $post['post_excerpt'] = $excerpt;
        }
    }
    
    function hide() {
        // do nothing
    }

}

?>